package com.config.shiro;

import com.utils.SerializableUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.io.Serializable;
import java.util.Collection;

/**
 * 对 Session 进行操作
 * 带缓存：EnterpriseCacheSessionDAO
 */
public class RedisSessionDAO extends AbstractSessionDAO {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 增加
     */
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);

        ValueOperations<Serializable, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(sessionId, SerializableUtils.serialize(session));

        String p = valueOperations.get(sessionId);
        System.out.println(p);
        return sessionId;
    }

    /**
     * 读取
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        ValueOperations<Serializable, String> valueOperations = redisTemplate.opsForValue();
        Serializable sessionStr = valueOperations.get(sessionId);
        if (sessionStr == null) {
            return null;
        }
        return SerializableUtils.deSerialize(sessionStr.toString());
    }

    /**
     * 更新
     */
    @Override
    public void update(Session session) throws UnknownSessionException {

    }

    /**
     * 删除
     */
    @Override
    public void delete(Session session) {

    }

    @Override
    public Collection<Session> getActiveSessions() {
        return null;
    }
}
